<template>
	<div class="FormList">
		<!-- 遍历表单对象的每个字段 -->
		<div v-for="(value, key) in form" :key="key" v-if="getVisible(formId, key) ||itemShow">
			<!-- 处理键为 notice_group_config 的对象字段 -->
			<div v-if="isObject(value) && key === 'notice_group_config'">
				<div style="font-weight: bold; margin-bottom: 10px;">{{ getLabel(formId, key) }}</div>
				<div class="FormItem">
					<formList :form="form[key]" :formId="`${formId}.${key}`"></formList>
				</div>
			</div>

			<!-- 处理数组类型字段 -->
			<div v-else-if="isArray(value) && value.length > 0">
				<div style="font-weight: bold; margin-bottom: 10px;">{{ getLabel(formId, key) }}</div>
				<div class="FormItem">
					<div v-for="(item, index) in value" :key="index">
						<!-- 处理数组中的字符串 -->
						<el-input v-if="isString(item)" v-model="value[index]" placeholder="请输入" />

						<!-- 处理数组中的对象 -->
						<!-- <formList v-if="isObject(item)" :form="item" :formId="`${formId}.${key}.${index}`"></formList> -->
						<div v-if="isObject(item)">
							<formList :form="item" :formId="`${formId}.${key}`"></formList>
						</div>
					</div>
				</div>
			</div>

			<!-- 处理普通键值对 -->
			<el-form-item v-else :label="getLabel(formId, key)" :class="{ 'red-label': isRedLabel(formId, key) }"
				label-width="auto">
				<template v-if="getType(formId, key) === 'text' ">
					<el-input v-model="form[key]" :placeholder="getPlaceholder(formId, key)" />
				</template>
				<template v-else-if="getType(formId, key) === 'number'">
					<el-input v-model.number="form[key]" :placeholder="getPlaceholder(formId, key)" type="number" />
				</template>
				<template v-else-if="getType(formId, key) === 'textarea'">
					<el-input type="textarea" v-model="form[key]" :placeholder="getPlaceholder(formId, key)" />
				</template>
				<template v-else-if="getType(formId, key) === 'image'">
					<div v-if="key === 'newHeadimgUrl'">
						<el-select v-model="form[key]" placeholder="请选择原始头像" clearable>
							<el-option v-for="item in headImgUrlList" :label="item.name" :key="item.name"
								:value="item.value">
							</el-option>
						</el-select>
					</div>
					<el-upload :ref="'uploadImage' + key" list-type="picture-card" :auto-upload="false"
						:on-change="(file, fileList) => changePositionPicList(file, fileList, key)" :limit="1"
						:multiple="false" :file-list="getImageFileList(key)">
						<i slot="default" class="el-icon-plus"></i>
						<div slot="file" slot-scope="{file}">
							<img class="el-upload-list__item-thumbnail" :src="form[key]" alt="">
							<span class="el-upload-list__item-actions">
								<span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
									<i class="el-icon-zoom-in"></i>
								</span>
								<span class="el-upload-list__item-delete" @click="handleRemovePositon(file, key)">
									<i class="el-icon-delete"></i>
								</span>
							</span>
						</div>
					</el-upload>
				</template>
			</el-form-item>
		</div>
		<div class="line" />
	</div>
</template>

<script>
	const OSS = require('ali-oss')
	import {
		beforeUpload1,
	} from '@/utils/compress';
	export default {
		name: 'formList',
		props: {
			form: {
				type: Object,
				required: true
			},
			formId: {
				type: String,
				required: true
			},
			itemShow:Boolean,
		},
		data() {
			return {
				headImgUrlList:[
					{
						name:'狮子（南师）',
						value:'/static/headImg/NNU_headImage.png',
					},
					{
						name:'老虎（南工程）',
						value:'/static/headImg/ngc.png',
					},
					{
						name:'猫（南财）',
						value:'/static/headImg/NUFE_headImage.png',
					}
				]
			}
		},
		created() {
			// console.log("组建中", this.form, this.formId)
			for (let i = 0; i < Object.keys(this.form).length; i++) {
				let str = Object.keys(this.form)[i]
				// console.log("数据类型", str, this.form[str], Object.prototype.toString.call(this.form[str]))
			}
		},
		methods: {
			getLabel(formId, key) {
				return this.$t(formId, key);
			},
			getType(formId, key) {
				return this.$type(formId, key);
			},
			getVisible(formId, key) {
				return this.$isVisible(formId, key);
			},
			isRedLabel(formId, key) {
				const isRed = this.$isRed(formId, key);
				// console.log(`Checking if ${key} in form ${formId} should be red:`, isRed);
				return isRed;
			},
			getPlaceholder(formId, key) {
				const placeholders = {
					text: '请输入',
					number: '请输入数字',
					textarea: '请输入',
					image: '上传图片'
				};
				return placeholders[this.getType(formId, key)] || '请输入';
			},
			handleUploadSuccess(response, file, fileList) {
				// 假设上传成功后的URL在response.url中
				console.log(4)
				this.$set(this.form, file.name, response.url);
			},
			//上传配置
			uploadConfig() {
				const client = new OSS({
					// yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
					region: '',
					// 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
					accessKeyId: '',
					accessKeySecret: '',
					// 填写Bucket名称。
					bucket: '',
					secure: 'true'
				});
				return client
			},
			async changePositionPicList(file, fileList, item) {
				// if (fileList.length > 0) {
				// 	this.form[item] = URL.createObjectURL(file.raw); // 临时预览使用
				// 	// 这里可以添加实际上传逻辑，上传成功后更新表单项
				// }
				console.log(file, fileList, item);
				// 获取对应的 image 对象
				let image = this.form[item];

				// fileList 中最后一个元素是最新添加的文件信息
				if (fileList.length > 0) {
					const latestFile = fileList[fileList.length - 1];
					// 假设你上传的响应有文件的 URL，替换 image.url
					// 需要根据实际响应结构调整这里的代码
					// image.url = latestFile.response.url;

					// 先压缩，再提交
					let img = await beforeUpload1(latestFile);
					console.log('压缩图', img);
					latestFile.raw = img;
					image = await this.pictureUploadUrl0507(latestFile, image);
					// 更新 form 中的 item
					this.$set(this.form, item, image);
				}
			},
			async pictureUploadUrl0507(file, image) {
				let client = this.uploadConfig();
				var fileName = 'configImg_' + new Date().getTime() + this.$store.state.user.currentSchool.schoolid;
				// 定义唯一的文件名，打印出来的uid其实就是时间戳
				return new Promise((resolve, reject) => {
					client.put('management_img/advImg/' + fileName, file.raw).then(
						result => {
							// 下面是如果对返回结果再进行处理，根据项目需要，下面是我们自己项目所用的，仅供参考
							// this.createContentForm.contenturl = this.createContentForm.contenturl +','+ result.url
							console.log('图片上传回调', result);
							result.url = result.url.replace('keming-bbs.oss-cn-shanghai.aliyuncs.com',
								'image.tanxiaojian.zone');
							resolve(result.url);
						},
						fail => {
							console.log(fail);
							reject(fail);
						}
					);
				});
			},
			handlePictureCardPreview(file) {
				this.$alert(`<img src="${file.url}" style="width: 100%">`, 'Preview', {
					dangerouslyUseHTMLString: true
				});
			},
			handleRemovePositon(file, item) {
				this.$set(this.form, item, ''); // 清空对应的表单项
			},
			getImageFileList(item) {
				return this.form[item] ? [{
					name: this.form[item],
					url: this.form[item]
				}] : [];
			},
			isObject(value) {
				return Object.prototype.toString.call(value) === '[object Object]';
			},
			isArray(value) {
				return Array.isArray(value);
			},
			isString(value) {
				return typeof value === 'string';
			}
		},
		watch: {
			"form": {
				handler(newVal, oldVal) {
					console.log(`新的值: ${newVal}`, newVal);
					console.log(`旧的值: ${oldVal}`, oldVal);
					//this.$emit("自定义的事件名称","要传递的参数")
					this.$emit("updateForm", this.form);
				},
				deep: true
			}
		}
	}
</script>

<style>
	.FormItem {
		padding: 10px;
		border: 1px solid #000;
		margin-bottom: 10px;
		border-radius: 10px;
	}

	.FormList {
		padding: 0 10px;
	}

	/* 横线 */
	.line {
		float: right;
		width: 100%;
		height: 1px;
		margin-top: -0.5em;
		background: #000000;
		position: relative;
		text-align: center;
		margin: 10px 0;
	}

	.red-label .el-form-item__label {
		color: red;
	}
</style>
